package com.bee.caf_ss_android;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bee.baselibrary.base.BaseActivity;
import com.bee.baselibrary.utils.MLog;
import com.bee.baselibrary.utils.T;
import com.bee.baselibrary.weight.TitleBar;
import com.bee.caf_ss_android.adapter.MyListAdapter;
import com.bee.caf_ss_android.common.Config;
import com.bee.caf_ss_android.common.GeneralReturnEntity;
import com.bee.caf_ss_android.common.ListBean;
import com.bee.caf_ss_android.common.LoadingDialog;
import com.bee.caf_ss_android.common.LocalStorage;
import com.bee.caf_ss_android.common.Tools;
import com.google.gson.Gson;
import com.jude.easyrecyclerview.decoration.DividerDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author LiHao 南柯一梦宁沉沦 不梦前程不梦卿
 * @org www.fengjishi.com (重庆蜂效电子商务有限公司)
 * @data Created time 2019/4/3.
 * @email 930176087@qq.com
 * @pakeage com.bee.caf_ss_android
 * Personal signature 余生还长 何必慌张
 * Page description : 个人主页
 */
public class PersonalActivity extends BaseActivity {
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.img_head)
    ImageView imgHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_shopName)
    TextView tvShopName;
    @BindView(R.id.tv_receptionCount)
    TextView tvReceptionCount;
    @BindView(R.id.main_setting)
    ImageView mainSetting;
    @BindView(R.id.m_recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    private LocalStorage localStorage;
    private LoadingDialog loadingDialog;

    private String token, counselorId;

    private Activity activity;

    private String TAG = "PersonalActivity";

    private Handler handler;

    public static Activity instance;
    private MyListAdapter adapter;
    private int page = 1;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_personal;
    }

    @Override
    protected void initData() {
        init();
    }

    @Override
    protected void initView() {

        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setNestedScrollingEnabled(false);
        adapter = new MyListAdapter(BaseActivity.context);
        mRecyclerView.setAdapter(adapter);

        //在没有更多数据的时候 底线更新列表移动
        refreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        localStorage = new LocalStorage(this);
        loadingDialog = new LoadingDialog(this, R.style.DialogStyle);
        activity = this;
        instance = this;
        handler = new Handler();

        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page = page + 1;
                getListData(false,page,false);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getListData(true,page,false);
            }
        });


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //移除定时器
        handler.removeCallbacksAndMessages(null);
    }

    private void init() {

        token = localStorage.getToken();
        counselorId = localStorage.getCounselorId();

        //先从缓存读取用户信息
        getCacheCounselorInfo();
        //再获取一次数据库内的信息
        getCounselorInfo();

        startActiveTimer();
        getListData(true,1,true);
    }

    private void getCacheCounselorInfo() {

        Log.d(TAG, "getCacheCounselorInfo: " + localStorage.getCounselorName());
        tvName.setText(localStorage.getCounselorName());
        tvShopName.setText(localStorage.getCounselorShopName());

    }

    /**
     * 开启定时向服务器推送活动
     * 让服务器知道自己还活着
     */
    private void startActiveTimer() {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                startActive();
                Log.d(TAG, "run: 定时器运行" + activity);
                //10分钟执行一次
                handler.postDelayed(this, 10 * 60 * 1000);
            }
        };
        handler.post(runnable);
    }

    private void startActive() {
        RequestParams requestParams = new RequestParams(Config.InterfaceHost + "app/activeToken");
        requestParams.addBodyParameter("token", token);
        requestParams.addBodyParameter("counselorId", counselorId);

        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                GeneralReturnEntity entity = JSONObject.parseObject(result, GeneralReturnEntity.class);

                //不等于代表有问题
                if (entity.getResCode() != 1) {
                    T.showLong(activity, entity.getErrMsg());
                    localStorage.cleanAllOutPhone();
                    Tools.refPage(activity, LoginActivity.class, true);

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    /**
     * 获取用户信息
     */
    private void getCounselorInfo() {
        RequestParams requestParams = new RequestParams(Config.InterfaceHost + "app/counselor/getInfo");
        requestParams.addBodyParameter("token", token);
        requestParams.addBodyParameter("counselorId", counselorId);
        loadingDialog.show();
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d(TAG, "onSuccess: " + result);
                GeneralReturnEntity entity = JSONObject.parseObject(result, GeneralReturnEntity.class);
                if (entity.getResCode() == -1) {
                    T.showLong(activity, entity.getErrMsg());
                } else {

                    JSONObject counselorInfo = JSONObject.parseObject(entity.getData());
                    String name = counselorInfo.getString("name"), shopName = counselorInfo.getString("shopName"), receptionCount = counselorInfo.getString("receptionCount");
                    tvName.setText(name);
                    tvShopName.setText(shopName == null ? "长安福特" : shopName);
                    tvReceptionCount.setText("接待人数：" + (receptionCount == null ? "0" : receptionCount));
                    //存入缓存
                    localStorage.setCounselorName(name);
                    localStorage.setCounselorShopName(shopName);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                loadingDialog.dismiss();
            }
        });
    }


    private void getListData(boolean isRefresh,int page,boolean isShowDialog){
        RequestParams rp = new RequestParams(Config.InterfaceHost + "app/counselor/getCallHistory");
        rp.addBodyParameter("counselorId", "00000169-e362-a867-821f-5d52c064cc5c");
        rp.addBodyParameter("token",token);
        rp.addBodyParameter("page",page+"");
        if (isShowDialog){
            loadingDialog.show();
        }

        x.http().get(rp, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MLog.e(result);
                ListBean listBean = new Gson().fromJson(result,ListBean.class);
                if (isRefresh){
                    refreshLayout.finishRefresh();
                    adapter.clear();
                    adapter.addAll(listBean.data);
                    refreshLayout.setNoMoreData(false);
                }else {
                    adapter.addAll(listBean.data);
                    if (listBean.data == null || listBean.data.size() < 10) {
                        ClassicsFooter.REFRESH_FOOTER_NOTHING = "- 没得数据了  翻个锤子 -";

                        refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                    } else {
                        refreshLayout.finishLoadMore();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                MLog.e(ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                loadingDialog.dismiss();
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
            }
        });
    };

    /**
     * 点击设置
     */
    public void onClickSetting(View view) {
        Tools.refPage(this, PersonalDataActivity.class, false);
    }
}
